package cn.edu.zisu.common.util.annotaion.interceptor;

import cn.edu.zisu.common.model.enumeration.BaseEnum;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;


import java.time.*;
import java.util.List;
/**
 * @author ymf
 * @date 2020/3/19
 */
public class JsonSerializerInterceptor extends JsonSerializer<Object> {

    private static final ZoneOffset CTT = OffsetDateTime.now(ZoneId.of(ZoneId.SHORT_IDS.get("CTT"))).getOffset();
    private static final String SEPARATE = ",";

    @Override
    public void serialize(Object object, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) {
        try {
            if (object instanceof Long) {
                jsonGenerator.writeString(object.toString());
            } else if (object instanceof LocalDateTime) {
                jsonGenerator.writeNumber(((LocalDateTime) object).toInstant(CTT).toEpochMilli());
            } else if (object instanceof LocalDate) {
                jsonGenerator.writeNumber(((LocalDate) object).atStartOfDay().toInstant(CTT).toEpochMilli());
            } else if (object instanceof BaseEnum) {
                jsonGenerator.writeNumber(((BaseEnum) object).getValue());
            } else if (object instanceof List<?>) {
                List<?> list = (List<?>) object;
                StringBuilder result = new StringBuilder();
                for (int i = 0; i < list.size(); i++) {
                    Object o = list.get(i);
                    if (o instanceof LocalDateTime) {
                        result.append(((LocalDateTime) o).toInstant(CTT).toEpochMilli());
                    } else if (o instanceof LocalDate) {
                        result.append(((LocalDate) o).atStartOfDay().toInstant(CTT).toEpochMilli());
                    } else if (o instanceof BaseEnum) {
                        result.append(((BaseEnum) o).getValue());
                    }
                    if (i != list.size() - 1) {
                        result.append(SEPARATE);
                    }
                }
                jsonGenerator.writeObject(result.toString());
            } else {
                jsonGenerator.writeObject(object);
            }
        } catch (Exception e) {
            throw new RuntimeException("序列化失败", e);
        }
    }
}